package com.ikingtech.framework.sdk.lock.lock;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class RedisDistributeLock implements DistributeLock{

    private final RedisLockRegistry redisLockRegistry;

    @Override
    public boolean tryLock(String lockKey, Long expireSecond) {
        Lock lock = redisLockRegistry.obtain(lockKey);
        try {
            return lock.tryLock(expireSecond, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("set distribute lock[{}] error{}", lockKey, e.getMessage());
            Thread.currentThread().interrupt();
            return false;
        } finally {
            lock.unlock();
            redisLockRegistry.expireUnusedOlderThan(60000L);
        }
    }

    @Override
    public void unlock(String lockKey) {
        try {
            Lock lock = redisLockRegistry.obtain(lockKey);
            lock.unlock();
            redisLockRegistry.expireUnusedOlderThan(60000L);
        } catch (Exception e) {
            log.error("unlock distribute lock[{}] error{}", lockKey, e.getMessage());
        }
    }
}
